package com.zcl.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zcl.entity.*;
import com.zcl.mapper.*;
import com.zcl.mapper.WorkerMapper;
import com.zcl.util.myBatisUtil;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

public class WorkerServiceImpl implements WorkerService {
    @Override
    public List<worker> findALL() {
        //查询所有员工
        try (SqlSession sqlSession = myBatisUtil.getSS(true);){
            WorkerMapper mapper = sqlSession.getMapper(WorkerMapper.class);
            deptMapper deptMapper=sqlSession.getMapper(deptMapper.class);
            List<worker> workers = mapper.findALL();
            //遍历员工列表
            for (worker worker : workers) {
                //获取部门编号
                 String did = worker.getDid();
                 dept dept = deptMapper.findById(did);
                 worker.setDname(dept.getDname());
            }
            return workers;
        }
    }
//保存员工
    @Override
    public void save(worker worker) {
        try (SqlSession sqlSession = myBatisUtil.getSS(true)){
            WorkerMapper mapper = sqlSession.getMapper(WorkerMapper.class);
            mapper.insert(worker);
        }
    }
//分页查询员工,带条件
    @Override
    public PageResult<worker> search(int page, int pageSize, WorkerVo workerVo) {
        //开始分页
        PageHelper.startPage(page,pageSize);
        //得到所有的数据
        List<worker> workers=this.findByWords(workerVo);
        Page<worker> workerPage=(Page<worker>)workers;
        return new PageResult<>(workerPage.getTotal(),workerPage.getResult());
    }
@Override
public List<worker> findByWords(WorkerVo workerVo) {
        try (SqlSession sqlSession = myBatisUtil.getSS(true);){
             //得到所有的mapper
            WorkerMapper mapper = sqlSession.getMapper(WorkerMapper.class);
            deptMapper deptMapper = sqlSession.getMapper(deptMapper.class);
            //根据条件查询员工
            List<worker>workers= mapper.findByWords(workerVo);
            //遍历员工列表,根据部门编号找到部门名称
            for (worker worker : workers) {
                //获取部门编号
                 String did = worker.getDid();
                 dept dept= deptMapper.findById(did);
                 worker.setDname(dept.getDname());
            }
            return workers;
        }
    }

    //分页查询
    @Override
    public PageResult<worker> findByPage(int page, int pageSize) {
//        开始分页
        PageHelper.startPage(page,pageSize);
        //得到全部的数据
        List<worker> workers = this.findALL();
        Page<worker> workerPage=(Page<worker>)workers;
        //返回分页结果集对象
        return new PageResult<>(workerPage.getTotal(),workerPage.getResult());
    }

}
